﻿#region Imports
using System;
using System.Windows;
using System.Windows.Controls;
using CommonUtilities.Extensions;
#endregion Imports

namespace BulkRenamer.App.WPF.Controls
{
    public class WatermarkTextBox : TextBox
    {
        bool SuppressTextChanged = false;

        private new TextChangedEventHandler TextChanged;
        private new RoutedEventHandler GotFocus;
        private new RoutedEventHandler LostFocus;

        private string watermarkText;
        public string WatermarkText
        {
            get { return watermarkText; }
            set { watermarkText = value; }
        }

        public WatermarkTextBox()
            : base()
        {
            this.TextChanged += new TextChangedEventHandler(WatermarkTextBox_TextChanged);
            this.GotFocus += new RoutedEventHandler(WatermarkTextBox_GotFocus);
            this.LostFocus += new RoutedEventHandler(WatermarkTextBox_LostFocus);
        }

        public void WatermarkTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //if (!SuppressTextChanged)
            //    if (this.Text == WatermarkText && this.IsFocused)
            //        this.Text = String.Empty;

            if (this.TextChanged != null) this.TextChanged(sender, e);
        }

        public void WatermarkTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.Text == WatermarkText)
                SuppressAndApplyChanges(new Action(() => this.Text = String.Empty));

            if (this.GotFocus != null) this.GotFocus(sender, e);
        }

        public void WatermarkTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (this.Text.IsBlank())
                SuppressAndApplyChanges(new Action(() => this.Text = WatermarkText));

            if (this.LostFocus != null) this.LostFocus(sender, e);
        }

        public void SuppressAndApplyChanges(Action action)
        {
            SuppressTextChanged = true;
            action();
            SuppressTextChanged = false;
        }
    }
}
